#include "pch.hpp"

#include <services/provider.hpp>
#include <logger/vsstream.hpp>

#include <engine.script/System.hpp>
#include <engine.debugger/duplex_queue.hpp>
#include <engine.debugger/Daemon.hpp>




void std_out_log(logger::entry e)
{
	std::cout << "[" << qPrintable(e.module) << "] " << logger::entry::toString(e.lvl) << ": " << qPrintable(e.message) << " (" << qPrintable(e.file) << ", line " << e.line << ")" << std::endl;
}
///////////////////////////////////////////////////////////////////////////////////////////////////

int main(int argc, char* argv[])
{
	try
	{
		if(argc < 2)
			throw boostext::exception("Missing argument: The second argument shall be the name of the script to execute");

		const char* script = argv[1];
		if(!boost::filesystem::exists(script))
			throw boostext::exception("The given script file does not exist");

		// Setup the service provider
		auto provider     = boost::make_shared<services::provider>();
		auto logger       = boost::make_shared<logger::vsstream>(provider);
		provider->registerService(logger);

		// Setup the scripting system
		auto scriptSystem = Engine::Script::System::create(&std_out_log);
		auto context      = scriptSystem->contextPool()->context();

		// Setup the debugger
		auto queue    = Engine::Debugger::duplex_queue<Engine::Debugger::Message>::ptr();
		auto debugger = Engine::Debugger::Daemon::create(queue, queue);
		scriptSystem->attach(debugger);

		// Run the script
		auto module = scriptSystem->moduleFromFile("main", script);
		scriptSystem->reflect();
		int id = module->functionIdByDecl("void main()");

		context->prepare(id);
		context->execute();

		return 0;
	}
	catch(boostext::exception& that)
	{
		std::cout << "Exception caught: " <<that.what() << std::endl;
	}
	catch(std::exception& that)
	{
		std::cout << "Exception caught: " <<that.what() << std::endl;
	}
	catch(...)
	{
		std::cout << "Unknown Exception caught" << std::endl;
	}

	return -1;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
